<?php

/**
* Controller 路由 控制器
*/

class Controller {

	public $defModule;
	public $defController;
	public $defAction;
	####
	public $moduleObj;
	public $module;
	public $action;

	public function __construct() {
		$this->init();
	}
	
	protected function init() {
		$this->loadConfig();
		$this->getParam();
		$this->loadController();
		$this->getAction();
		$this->doAction();
	}
	
	protected function getParam() {
		$_module = isset($_REQUEST['m']) ? trim(strip_tags($_REQUEST['m'])) : '';
		$this->module = $_module != '' ? $_module : $this->defModule;
		$_controller = isset($_REQUEST['c']) ? trim(strip_tags($_REQUEST['c'])) : '';
		$this->controller = $_controller != '' ? $_controller : $this->defController;
		$_action = isset($_REQUEST['a']) ? trim(strip_tags($_REQUEST['a'])) : '';
		$this->action = $_action != '' ? $_action : $this->defAction;
	}
	
	protected function getAction() {
		method_exists($this->controller, $this->action) || $this->action = $this->defAction;
		define('ACTION_NAME', $this->action);
		$jurisdiction = new ReflectionMethod($this->controller, $this->action);
		$ModifierNames = implode(' ', Reflection::getModifierNames($jurisdiction->getModifiers()));
		$ModifierNames != 'public' && $ModifierNames != 'public static' && $this->action = $this->defAction;
		//if ($ModifierNames != 'public' && $ModifierNames != 'public static') die('No permission !');
	}
	
	protected function checkModuleController() {
		//clearstatcache(); // 清楚文件缓存
		if (!is_dir(WEB_PATH . "/apps/" . $this->module)) {
			if (!is_dir(WEB_PATH . "/apps/" . $this->defModule)) die('ERROR: No Module [' . $this->module . ']');
			$this->module = $this->defModule;
		}
		$controlFile = WEB_PATH . '/apps/' . $this->module . '/' . $this->controller . '.ctrl.php';
		if (!file_exists($controlFile)) {
			$controlFile_def = WEB_PATH . '/apps/' . $this->module . '/' . $this->defController . '.ctrl.php';
			if (!file_exists($controlFile_def)) die('ERROR: No Controller [' . $this->controller . ']');
			$this->controller = $this->defController;
		}
		//!$flag && die('No such module file found');
		return true;
	}
	
	protected function loadController() {
		$this->checkModuleController();
		define('MODULE_NAME', $this->module);
		define('CONTROLLER_NAME', $this->controller);
		define('TEMP_PATH', './template/' . $this->module . '/' . $this->controller . '/');
		$controllerFile = WEB_PATH . "/apps/{$this->module}/" . $this->controller . '.ctrl.php';
		include $controllerFile;
	}
	
	protected function doAction() {
		$this->controllerObj = new $this->controller;
		$action = $this->action;
		$this->controllerObj->$action();
	}
	
	protected function loadConfig() {
		$conf = System::$config['Controller'];
		$this->defModule = $conf['defModule'];
		$this->defController = $conf['defController'];
		$this->defAction = $conf['defAction'];
	}
}